<?php
namespace App\Http\ViewComposers;

use App\Events\SystemNotify;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Group;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use App\Models\User;
use App\Models\RoleUser;
use App\Models\RewardPunishDetail;


//pc端左侧共用通讯录
class PcComposer
{
    private $user;
    private $corpid;
    private $tongxunlu;

    public function __construct()
    {
        if(empty(Auth::user())){
            abort(403,'登录信息错误');
        }
        $user = Auth::user()->comuser();
        if(empty($user)){
            abort(403,'登录信息错误');
        }
        $this->user = $user;
        $this->corpid = $user->corpid;
        
        //获取组
        $tongxunlu = array();
        $groups = Group::where('corpid',$this->corpid)->select('id','group_name','fid','class_id')->get();
        $groups = $groups->toArray();
        $groups_add = array('id'=>0,'group_name'=>'我的同事','fid'=>'undefined','class_id'=>1);
        array_unshift($groups,$groups_add);

        $users = User::where('corpid',$this->corpid)->select('id','qw_userid','qw_name','group_id','is_leader')->get();
        foreach ($groups as &$g){
            $g['count'] = $this->filterUser($g['id'],$users);
            if($g['fid'] == 0){
                $tongxunlu[] = $g;
            }
        }
        foreach ($tongxunlu as $k=>&$t){
            if($t['id'] !=0){
                $t['child'] = $this->filterGroup($t['id'],$groups);
                foreach ($t['child'] as &$cld){
                    $cld['child'] = $this->filterGroup($cld['id'],$groups);
                }
            }
        }
        $this->tongxunlu  = $tongxunlu;


    }
    
    public function compose(View $view)
    {
        $view->with('tongxunlu',$this->tongxunlu);
    }

    private function filterGroup($group_id,$groups){
        $return = array();
        foreach ($groups as $u){
            if($u['fid'] == $group_id){
                $return[] = $u;
            }
        }
        return $return;
    }

    //筛选用户
    private function filterUser($group_id,$users){
        $return = 0;
        foreach ($users as $u){
            if($u['group_id'] == $group_id){
                $return += 1;
            }
        }
        return $return;
    }
}